--[[
   Copyright (c) 2012 TPV R&D Center Brazil
   All rights reserved

   FileName: gui.zapping

   Created by: LPaes
   Date: 21/08/2012
--]]
------------------------------------------------------------------------
--requires
local tInputApp = require('input')
local tChannelApp = require('channel')
local tPrefenceApp = require('preference')
require('basicZapper')
require('graphic-toolkit.toolkit.guilt')
require('IterateTimer')
------------------------------------------------------------------------
-- Local variables
local bIsFastzapper  = false
local tChannelNextPrevious = {}
local labelNumber = nil
local windowNumber = nil
local tTimeOut = nil
local tFastTimeOut = nil
local nFastTimeout = 500
local nOSDTimeout = 3000
local lenghtChannel = 2
local ChannelList =  channels.getChannelList()
local setChannel = ""
tZappingGui = {}
------------------------------------------------------------------------
--auxiliar functions

-- Function to select channel.
local function selectChannel()
   local bRet = false
   local tChan = tChannelApp.getCurrentChannel()
   if (tChan.nId ~= tChannelNextPrevious.nId) then
      bRet = true
      tChannelApp.selectChannel(tChannelNextPrevious)
   end
   if (bIsFastzapper) then
      tFastTimeOut:reset()
   else
      bIsFastzapper = true
      tFastTimeOut = nil
      tFastTimeOut = IterateTimer:new(nFastTimeout, tZappingGui.fastTimeOutChecker, 1)
      tFastTimeOut:start()
   end
   tChan = nil
   return bRet
end

-- Synchronous function to create zapping screen.



-- modifiquei muita coisa desse create
local function create()
   -- Window to show OSD
   windowNumber = Window:new({width = 1280, height = 262})
   local boxNumber = Box:new()
   boxNumber:setAnchors({fill = windowNumber})

   local imageShadow = Image:new({z = 1, fileName = 'resources/images/channel-number-bg.png'})
   imageShadow:setAnchors({left = boxNumber.left, top = boxNumber.top})
   

   labelNumber = Label:new({z = 2, width = 1000, height = 105})
  
   labelNumber:setActivated({size = 100, color = {241, 241, 241, 255}})
   labelNumber:setShadow()
   labelNumber:setAnchors({left = boxNumber.left, 
                           top = boxNumber.top, 
                           leftMargin = 34, 
                           topMargin = 18})
   --~ if (tChannelNextPrevious.isDigital) then
   --~ 
       --~ labelNumber:setText('' .. tChannelNextPrevious.number .. '.' .. tChannelNextPrevious.service)
     --~ 
   --~ else
       --~ labelNumber:setText('' .. tChannelNextPrevious.number)
      --~ 
   --~ end
   
   
    if (control.getCurrentChannel().isDigital) then
   
       labelNumber:setText('' .. control.getCurrentChannel().number .. '.' .. control.getCurrentChannel().service)
     
   else
       labelNumber:setText('' .. control.getCurrentChannel().number)
      
   end
   boxNumber:add({imageShadow, labelNumber})
   windowNumber:compose(boxNumber)
   imageShadow = nil
   boxNumber = nil
end


function createNumber(number)
	print("chamou o createNUmber com o numero")
	print(number)
	  -- Window to show OSD
   tStackWindow = StackWindow:new()
   windowNumber = Window:new({width = 1280, height = 262})
   local boxNumber = Box:new()
   boxNumber:setAnchors({fill = windowNumber})

   local imageShadow = Image:new({z = 1, fileName = 'resources/images/channel-number-bg.png'})
   imageShadow:setAnchors({left = boxNumber.left, top = boxNumber.top})
   

   labelNumber = Label:new({z = 2, width = 1000, height = 105})
  
   labelNumber:setActivated({size = 100, color = {241, 241, 241, 255}})
   labelNumber:setShadow()
   labelNumber:setAnchors({left = boxNumber.left, 
                           top = boxNumber.top, 
                           leftMargin = 34, 
                           topMargin = 18})
   --~ if (tChannelNextPrevious.isDigital) then
   --~ 
       --~ labelNumber:setText('' .. tChannelNextPrevious.number .. '.' .. tChannelNextPrevious.service)
     --~ 
   --~ else
       --~ labelNumber:setText('' .. tChannelNextPrevious.number)
      --~ 
   --~ end
   
   
    if (control.getCurrentChannel().isDigital) then   
       labelNumber:setText(number)     
   else   
       labelNumber:setText(number)      
   end
   
   boxNumber:add({imageShadow, labelNumber})
   windowNumber:compose(boxNumber)
   imageShadow = nil
   boxNumber = nil
   tStackWindow:replace(windowNumber)
end


function changeChannelByNumberZapping(numberChannel)
	numberChannel = tostring(tonumber(numberChannel))	
	if #setChannel < lenghtChannel then
		
		setChannel = setChannel..numberChannel	
		
		if(cancelChangeChannel) then
			cancelChangeChannel()
		end		
		
		
		createNumber(setChannel)		
		
		cancelChangeChannel = event.timer(2000, function()						
			for i,v in ipairs(ChannelList) do				
				if(tostring(tonumber(setChannel)) == tostring(v.physNumber)) then						
					idChannel = v.id -- quando mudar o canal, atualizar a varivavel que controla a direção para cima e para baixo
					
					lastChannelId = control.getCurrentChannel().id    -- salvar o ultimo canal
					control.selectChannel(v.id)	
					setChannel = ""	
					
					event.timer(1000, function()					
						--metodos de esconder a interface grafica--
						hide()
						dispose()	
					end)					
							
					return
				end				
			end
				
				print("nao tem canal")				
				--canvas:compose(1198,38,iconNoAction)			
				
				event.timer(1000, function()
					lenghtChannel= 2
					--metodos de esconder a interface grafica--
					hide()
					dispose()					
				end)			
			
			setChannel = ""			
			print("resetei tudo")
		end)
	end
end


























-- Synchronous function to show object zapping by setText from toolKit API.
local function show()
   --~ if (tChannelNextPrevious.bIsDigital) then
       --~ labelNumber:setText('' .. tChannelNextPrevious.nNumber .. '.' .. tChannelNextPrevious.nService)
   --~ else
       --~ labelNumber:setText('' .. tChannelNextPrevious.nNumber)
   --~ end
   
    if (tChannelNextPrevious.bIsDigital) then
       labelNumber:setText('' .. tChannelNextPrevious.nNumber .. '.' .. tChannelNextPrevious.nService)
   else
       labelNumber:setText('' .. tChannelNextPrevious.nNumber)
   end
   labelNumber:redraw()
end

-- Synchronous function to hide object zapping.
function hide()
   tStackWindow:pop()
end

-- Synchronous function to dispose object zapping.
 function dispose()
   bIsFastzapper = false
   tChannelNextPrevious = nil
   labelNumber = nil
   windowNumber:dispose()
   windowNumber = nil
   if (tFastTimeOut ~= nil) then
      tFastTimeOut:stop()
      tFastTimeOut = nil
   end
   if (tTimeOut ~= nil) then
      tTimeOut:stop()
      tTimeOut = nil
   end
end
------------------------------------------------------------------------
--module table
--module description - This is a template of an GUI Screen module
------------------------------------------------------------------------
--module functions

--- Callback function for a Tv-Stack to request channel up and channel down.
-- @param sKey: It is a call back to get CHANNEL_UP, CHANNEL_DOWN.
-- @return CHANNEL_UP, or CHANNEL_DOWN. 
function tZappingGui.open(sKey)
	print("entrou no tZapping.open")	
   local sSource = tInputApp.getCurrentSource()
   print(sSource)
   if (sSource.sName ~= "TV") then      
      tZappingGui.tControllerHandler.onNoAction()
      tZappingGui.tControllerHandler.close()      
   else
	
      --local nChanListSize = tChannelApp.getChannelListSize()
      local nChanListSize = #channels.getChannelList()     
      local tTempCurrChan = control.getCurrentChannel()   
      if (nChanListSize > 1) then
     
         --create GUI
         if (sKey == 'CHANNEL_UP') then
			
            tChannelNextPrevious = getNextChannel(tTempCurrChan)
           
            if (tChannelNextPrevious.id == tTempCurrChan.id or tChannelNextPrevious.nId == nil) then
               tChannelNextPrevious = tTempCurrChan
            end
         elseif (sKey == 'CHANNEL_DOWN') then
            tChannelNextPrevious = getPreviousChannel(tTempCurrChan)
            if (tChannelNextPrevious.id == tTempCurrChan.id or tChannelNextPrevious.id == nil) then
               tChannelNextPrevious = tTempCurrChan
            end
         elseif (sKey == 'ZAPPING') then
            tChannelNextPrevious = tTempCurrChan
         end
		 tStackWindow = StackWindow:new()	
			
         create()
         
         tStackWindow:replace(windowNumber)
         
         --tChannelApp.selectChannel(tChannelNextPrevious)
         --start timeout
         
         tTimeOut = IterateTimer:new(nOSDTimeout, tZappingGui.timeOutChecker, 1)
         tTimeOut:start()
         
         bIsFastzapper = true
         
         tFastTimeOut = IterateTimer:new(nFastTimeout, tZappingGui.fastTimeOutChecker, 1)
         tFastTimeOut:start()
         
         
      elseif (nChanListSize == 1) then
         tZappingGui.tControllerHandler.onNoAction()
         tZappingGui.tControllerHandler.close()--@TODO integrate with no Action
      else
         tZappingGui.tControllerHandler.onNoAction()
         tZappingGui.tControllerHandler.close()--@TODO integrate with no Action
      end
   end
   sSource = nil
   nChanListSize = nil
end

---------- implementado por nós do secondScreen ---------------
function getNextChannel(actualChannel)
	print("o numero do canal antes de mudar")
	print(actualChannel.physNumber)
	local ChannelList = channels.getChannelList()
	
	
	for i,v in ipairs (ChannelList) do		
		if (v.name == actualChannel.name) then
			if(i == (#ChannelList)) then
				return ChannelList[1]
			end			
			return ChannelList[i + 1]
		end
	end
	return nil
end					
	 
	 
---------- implementado por nós do secondScreen ---------------	 
function getPreviousChannel(actualChannel)

	local ChannelList = channels.getChannelList()	
	for i,v in ipairs (ChannelList) do		
		if (v.name == actualChannel.name) then
			if(i == 1) then
				return ChannelList[#ChannelList]
			end			
			return ChannelList[i]
		end
	end
	return nil
end		 
--- This function close zapping gui.
-- @usage
function tZappingGui.close(sKey)
   --stop timeout
   if (tFastTimeOut ~= nil) then
      tFastTimeOut:stop()
      tFastTimeOut = nil
   end
   if (tTimeOut ~= nil) then
      tTimeOut:stop()
      tTimeOut = nil
   end
   --close GUI
   hide()
   dispose()
   --inform controller
   tZappingGui.tControllerHandler.close(sKey)
end

--- Synchronous function to put a timer verify if zapping was stopped.
-- @usage
function tZappingGui.fastTimeOutChecker()
   bIsFastzapper = false
   tFastTimeOut = nil
   selectChannel()
end

function tZappingGui.timeOutChecker()
   tTimeOut = nil
   tZappingGui.close()
end

---Function to process remote control event.
-- @param sKey INFO: Remote control KEY pressed.
function tZappingGui.onCommand(sKey)
   --reset timeout
   if (bIsFastzapper) then
      tFastTimeOut:reset()
   end
   tTimeOut:reset()
   --handle key
   if (sKey == 'CHANNEL_UP') then
      tChannelNextPrevious = tChannelApp.getNextChannel(tChannelNextPrevious)
      print("passou da variavel tChannelNextPrevious")
      if (not bIsFastzapper) then
         bIsFastzapper = true
         tFastTimeOut = nil
         tFastTimeOut = IterateTimer:new(nFastTimeout, tZappingGui.fastTimeOutChecker, 1)
         tFastTimeOut:start()
      end
      --show GUI
      show()
   elseif (sKey == 'CHANNEL_DOWN') then
      tChannelNextPrevious = tChannelApp.getPreviousChannel(tChannelNextPrevious)
      if (not bIsFastzapper) then
         bIsFastzapper = true
         tFastTimeOut = nil
         tFastTimeOut = IterateTimer:new(nFastTimeout, tZappingGui.fastTimeOutChecker, 1)
         tFastTimeOut:start()
      end
      --show GUI
      show()
   elseif (sKey == 'ENTER') then
      selectChannel()
      tZappingGui.close()
   elseif (sKey == 'RED') or (sKey == 'GREEN')
      or (sKey == 'BLUE') or (sKey == 'YELLOW') 
      or (sKey == 'DISPLAY_ZAPPING') or (sKey == 'ZAPPING')
      or (sKey == 'CURSOR_UP') or (sKey == 'CURSOR_DOWN') 
      or (sKey == 'CURSOR_LEFT') or (sKey == 'CURSOR_RIGHT') then
      -- do nothing
   else
      tZappingGui.close(sKey)
   end
end
------------------------------------------------------------------------
--handlers to controller
tZappingGui.tControllerHandler = {}

-- Synchronous function
-- @usage
function tZappingGui.tControllerHandler.close(sKey)
end

function tZappingGui.tControllerHandler.onNoAction()
end
------------------------------------------------------------------------
return tZappingGui
